package com.gentlemancredit.app.utils;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.Telephony;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.gentlemancredit.app.bean.CallRecord;
import com.gentlemancredit.app.bean.PhoneDto;
import com.gentlemancredit.app.bean.SMSMessage;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class PhoneUtil {
    // 号码
    public final static String NUM = ContactsContract.CommonDataKinds.Phone.NUMBER;
    // 联系人姓名
    public final static String NAME = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;

    //上下文对象
    private Context context;
    //联系人提供者的uri
    private Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;


    public PhoneUtil(Context context) {
        this.context = context;
    }

    //获取所有联系人
    public List getPhone() {
        List<PhoneDto> phoneDtos = new ArrayList<>();
        ContentResolver cr = context.getContentResolver();
        Cursor cursor = cr.query(phoneUri, new String[]{NUM, NAME}, null, null, null);
        while (cursor.moveToNext()) {
            PhoneDto phoneDto = new PhoneDto(cursor.getString(cursor.getColumnIndex(NAME)), cursor.getString(cursor.getColumnIndex(NUM)));
            phoneDtos.add(phoneDto);
        }
        Map<String, List<String>> data = new HashMap<>();
        if (phoneDtos != null && phoneDtos.size() != 0) {
            for (int i = 0; i < phoneDtos.size(); i++) {
                PhoneDto phoneDto = phoneDtos.get(i);
                if (null == data.get(phoneDto.getName())) {
                    ArrayList phoneList = new ArrayList();
                    phoneList.add(phoneDto.getPhone());
                    data.put(phoneDto.getName(), phoneList);
                } else {
                    List<String> strings = data.get(phoneDto.getName());
                    strings.add(phoneDto.getPhone());
                }
            }
        }

        List result = new ArrayList();
        for (String key : data.keySet()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", key);
            jsonObject.put("phoneNumers", data.get(key));
            result.add(jsonObject);
        }

        return result;
    }


    /**
     * CallLog.Calls.CACHED_FORMATTED_NUMBER      通话记录格式化号码
     * CallLog.Calls.CACHED_MATCHED_NUMBER     通话记录为格式化号码
     * CallLog.Calls.CACHED_NAME     联系人名称
     * CallLog.Calls.TYPE    通话类型
     * CallLog.Calls.DATE    通话时间(long型)
     * CallLog.Calls.DURATION     通话时长(秒为单位)
     * CallLog.Calls.GEOCODED_LOCATION    运营商地址(如：浙江杭州)
     * <p>
     * 通话类型
     * CallLog.Calls.INCOMING_TYPE      呼入
     * CallLog.Calls.OUTGOING_TYPE      呼出
     * CallLog.Calls.MISSED_TYPE       未接
     *
     * @return
     */
//    @SuppressLint("MissingPermission")
    public List<CallRecord> getCallLog() {
        List<CallRecord> list = new ArrayList<>();
        ContentResolver resolver = context.getContentResolver();
        //获取cursor对象
        Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, new String[]{
                CallLog.Calls.CACHED_FORMATTED_NUMBER,
                CallLog.Calls.CACHED_MATCHED_NUMBER,
                CallLog.Calls.CACHED_NAME,
                CallLog.Calls.TYPE,
                CallLog.Calls.DATE,
                CallLog.Calls.DURATION,
                CallLog.Calls.GEOCODED_LOCATION,
        }, null, null, "date DESC ");
        if (cursor != null) {
            Log.i("TAG", "cursor length is " + cursor.getCount());
            try {
                while (cursor.moveToNext()) {
                    CallRecord record = new CallRecord();
                    record.formatted_number = cursor.getString(0);
                    record.matched_number = cursor.getString(1);
                    record.name = cursor.getString(2);
                    record.type = getCallType(cursor.getInt(3));
                    record.date = cursor.getLong(4);
                    record.duration = cursor.getLong(5);
                    record.location = cursor.getString(6);
                    list.add(record);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cursor.close();  //关闭cursor，避免内存泄露
            }
        }

        return list;
    }

    public String formatDate(long time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
        return format.format(new Date(time));
    }

    //通话类型转话代码：
    private String getCallType(int anInt) {
        switch (anInt) {
            case CallLog.Calls.INCOMING_TYPE:
                return "呼入";
            case CallLog.Calls.OUTGOING_TYPE:
                return "呼出";
            case CallLog.Calls.MISSED_TYPE:
                return "未接";
            default:
                break;
        }
        return null;
    }


    /**
     * Telephony.Sms.ADDRESS     发件人地址，即手机号
     * Telephony.Sms.BODY      短信具体内容
     * Telephony.Sms.DATE      日期，long型
     * Telephony.Sms.READ      是否阅读0未读，1已读
     * Telephony.Sms.STATUS     短信状态-1 接收，0 complete,64 pending,128 failed
     * Telephony.Sms.TYPE      短信类型1是接收到的，2是已发出
     *
     * @return
     */
    public List<SMSMessage> getSms() {
        List<SMSMessage> list = new ArrayList<>();
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(Telephony.Sms.CONTENT_URI, new String[]{
                Telephony.Sms.ADDRESS,   //
                Telephony.Sms.BODY,
                Telephony.Sms.DATE,
                Telephony.Sms.READ,
                Telephony.Sms.STATUS,
                Telephony.Sms.TYPE,
        }, null, null, "date DESC");
        if (cursor != null) {
            while (cursor.moveToNext()) {
                SMSMessage message = new SMSMessage();
                message.address = cursor.getString(0);
                message.body = cursor.getString(1);
                message.date = cursor.getLong(2);
                message.read = getMessageRead(cursor.getInt(3));
                message.status = getMessageStatus(cursor.getInt(4));
                message.type = getMessageType(cursor.getInt(5));
                message.person = getPerson(message.address);
                list.add(message);
            }
            cursor.close();
        }
        return list;
    }

    //短信阅读状态代码：
    private String getMessageRead(int anInt) {
        if (1 == anInt) {
            return "已读";
        }
        if (0 == anInt) {
            return "未读";
        }
        return null;
    }

    //短信类型区分代码
    private String getMessageType(int anInt) {
        if (1 == anInt) {
            return "收到的";
        }
        if (2 == anInt) {
            return "已发出";
        }
        return null;
    }

    //短信接收状态代码：
    private String getMessageStatus(int anInt) {
        switch (anInt) {
            case -1:
                return "接收";
            case 0:
                return "complete";
            case 64:
                return "pending";
            case 128:
                return "failed";
            default:
                break;
        }
        return null;
    }

    //短信发件人代码，发件人，如果发件人在通讯录中则为具体姓名，陌生人为null：
    private String getPerson(String address) {
        try {
            ContentResolver resolver = context.getContentResolver();
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, address);
            Cursor cursor;
            cursor = resolver.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
            if (cursor != null) {
                try {
                    if (cursor.getCount() != 0) {
                        cursor.moveToFirst();
                        String name = cursor.getString(0);
                        return name;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    cursor.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
